<?php
namespace App\Http\Controllers\api;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\DB;
use App\Models\MyLog;
use App\Models\Mongodb;
require_once('function.php');
require_once('moban.php');

/**
 *
 * 微信支付回调
 */


class NotifyController extends Controller
{
    // protected $pay_apikey = 'FgfdDGsV567ADSFsddVLK554642DddSm';//key

    public function notify()
    {
        $xml = $this->post_data();

        //将服务器返回的XML数据转化为数组
        $data = $this->xml2array($xml);
        // 保存微信服务器返回的签名sign
        $data_sign = $data['sign'];
        // sign不参与签名算法
        unset($data['sign']);
        $sign = $this->makeSign($data);

        $mylog = new MyLog;
        $mylog->setLog('支付回调：'.$xml, $logPath = 'wePay');

        // 判断签名是否正确  判断支付状态
        if (($sign === $data_sign) && ($data['return_code'] == 'SUCCESS') && ($data['result_code'] == 'SUCCESS')) {
            $result = $data;
            //获取服务器返回的数据
            $order_sn = $data['out_trade_no'];            //订单单号
            $openid = $data['openid'];                    //付款人openID
            $total_fee = $data['total_fee'];            //付款金额
            $transaction_id = $data['transaction_id'];     //微信支付流水号

            DB::beginTransaction();//事务
            try {

                $order_update = DB::table('cdorder')->where('order_sn', $order_sn)->increment('one', 1, ['pay_status' => 1, 'pay_time' => time(), 'transaction_id' => $transaction_id]);
                $redf_update = DB::table('redf')->where('order_sn', $order_sn)->update(['status' => 1]);//更新发红包表状态
                $form = DB::table('cdorder')->where('order_sn', $order_sn)->first();//查询订单表

                if ($order_update && $redf_update) {
                    DB::commit();//成功，提交事务
                    //echo 'success';

                    if ($form->one === 1) {//one 判断回调一次则执行第二次不执行
                        DB::table('wallet')->where('openid', $openid)->update(['money' => 0]);//更新零钱
                    }

                    //发送模板消息
                    $info = DB::table('redf')->select('id', 'password','sign')->where('order_sn', $order_sn)->first();//查询更新的红包id
                    $moban = new \Moban();
                    $mobanData = [
                        'keyword1' => ['value' => $info->password],
                        'keyword2' => ['value' => date("Y-m-d H:i")],
                        'keyword3' => ['value' => '点击此处查看口令详情']
                    ];
                    $formid = $form->prepay_id;
                    if ($info->sign == 1) {
                        $res = $moban->send($data['openid'], 'F0DiI5B2L4ousaXKRC7I6dvKS5EmiErzdjZOsM_QYkw', 'pages/voice_box/parcel_detail/index?id=' . $info->id, $formid, $mobanData);
                    }else {
                        $res = $moban->send($data['openid'], 'F0DiI5B2L4ousaXKRC7I6dvKS5EmiErzdjZOsM_QYkw', 'pages/voice_box/guess/index?id=' . $info->id, $formid, $mobanData);
                    }

                    //回调数据库日志
                    $logs = Mongodb::connectionMongodb('hb_log');
                    $logs->insert(['order_sn' => $order_sn, 'openid' => $openid, 'type' => '1', 'name' => '支付回调', 'message' => $xml, 'log_time' => date("Y-m-d H:i")]);
                    $logs->insert(['order_sn' => $order_sn,'name' => '支付模板消息错误码','type' => '2','openid' => $openid,'message' => $res->errmsg,'log_time' => date("Y-m-d H:i") ]);
                }

            } catch (\Exception $e) {
                $mylog = new MyLog;
                $mylog->setLog('回调事务数据异常:' . $e, $logPath = 'notify');
                DB::rollBack();//失败，回滚事务
                echo 'error';
                //return false;
            }



        } else {
            $result = false;
        }
        // 返回状态给微信服务器
        if ($result) {
            $str = '<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>';
        } else {
            $str = '<xml><return_code><![CDATA[FAIL]]></return_code><return_msg><![CDATA[签名失败]]></return_msg></xml>';
        }
        echo $str;
        return $result;
    }



    //微信支付回调接收方法
    public function post_data()
    {
        $receipt = $_REQUEST;
        if ($receipt == null) {
            $receipt = file_get_contents("php://input");
            if ($receipt == null) {
                $receipt = $GLOBALS['HTTP_RAW_POST_DATA'];
            }
        }
        return $receipt;
    }

    /**
     * 将xml转为array
     * @param  string $xml xml字符串
     * @return array    转换得到的数组
     */
    protected function xml2array($xml)
    {
        //禁止引用外部xml实体
        libxml_disable_entity_loader(true);
        $result = json_decode(json_encode(simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA)), true);
        return $result;
    }

    /**
     * 生成签名
     * @return 签名
     */
    protected function makeSign($data)
    {
        //获取微信支付秘钥
        $key = env('WXPAY_API_KEY');
        // 去空
        $data = array_filter($data);
        //签名步骤一：按字典序排序参数
        ksort($data);
        $string_a = http_build_query($data);
        $string_a = urldecode($string_a);
        //签名步骤二：在string后加入KEY
        //$config=$this->config;
        $string_sign_temp = $string_a . "&key=" . $key;
        //签名步骤三：MD5加密
        $sign = md5($string_sign_temp);
        // 签名步骤四：所有字符转为大写
        $result = strtoupper($sign);
        return $result;
    }
}